<template>
  <div class="container">
    <el-tabs v-model="activeName">
      <el-tab-pane label="用户充值" name="0">
        <div class="top-search">
          <el-date-picker
            v-model="datePicker[0]"
            class="w-240"
            type="daterange"
            align="right"
            value-format="yyyy-MM-dd"
          />
          <el-select v-model="listQuery[0].operatorType" class="w-240">
            <el-option
              v-for="item in operatorsOption"
              :label="item.label"
              :value="item.value"
              :key="item.label"
            />
          </el-select>
          <el-select v-model="listQuery[0].paymentType" class="w-240">
            <el-option
              v-for="item in payMethodOption"
              :label="item.label"
              :value="item.value"
              :key="item.label"
            />
          </el-select>
          <el-input
            :value="listQuery[0].memberId"
            class="w-240"
            placeholder="用户ID"
            maxlength="18"
            clearable
            @input="
              (value) => (listQuery[0].memberId = value.replace(/[^\d]/g, ''))
            "
          />
          <el-input
            :value="listQuery[0].mobile"
            class="w-240"
            placeholder="充值号码"
            maxlength="18"
            clearable
            @input="
              (value) => (listQuery[0].mobile = value.replace(/[^\d]/g, ''))
            "
          />
          <el-input
            :value="listQuery[0].orderSn"
            class="w-240"
            placeholder="订单号"
            clearable
            @input="
              (value) => (listQuery[0].orderSn = value.replace(/[^\d]/g, ''))
            "
          />
          <el-button type="primary" @click="search(0)">搜索</el-button>
          <el-button
            :disabled="total[0] == 0"
            class="fr"
            type="primary"
            @click="toExport(0)"
            >导出</el-button
          >
          <span class="summary_total fr"> {{ $t('total_amount') }}: {{ billTotal[activeName] }} </span>
        </div>

        <el-row>
          <el-col class="p-t-20">
            <el-table
              v-loading="listLoading[0]"
              :data="listData[0]"
              border
              fit
              highlight-current-row
            >
              <el-table-column label="Serial number" width="80" align="center">
                <template slot-scope="scope">
                  <span>{{
                    (listQuery[0].pageNum - 1) * listQuery[0].pageSize +
                      scope.$index +
                      1
                  }}</span>
                </template>
              </el-table-column>

              <el-table-column label="Order Sn" prop="orderSn" align="center"/>

              <el-table-column
                label="Telecom Operator"
                prop="rechargeOperator"
                align="center"
              />

              <el-table-column
                label="Mobile/Account"
                prop="mobile"
                align="center"
              />

              <el-table-column label="Member ID" prop="memberId" align="center"/>

              <el-table-column
                label="Currency Type"
                prop="currencyType"
                align="center"
              />

              <el-table-column
                label="Top-up Status"
                align="center"
              >
                <template slot-scope="{row}">
                  <span>{{ row.topUpStatus }}</span>
                  <el-button size="mini" type="primary" @click="edit(row, 0)">修改状态</el-button>
                </template>
              </el-table-column>

              <el-table-column label="Amount（$）" prop="amount" align="center"/>

              <el-table-column
                label="Transaction_id"
                prop="transactionId"
                align="center"
              />

              <el-table-column
                label="Order Status"
                prop="orderStatus"
                align="center"
              />

              <el-table-column
                label="Payment Account（¥/$）"
                prop="paymentAmount"
                align="center"
              />

              <el-table-column
                label="Payment Type"
                prop="paymentType"
                align="center"
              />

              <el-table-column label="Pay Time" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.payTime | fmtdate }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="Payment Status"
                prop="paymentStatus"
                align="center"
              />

              <el-table-column label="Complete Time" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.completeTime | fmtdate }}</span>
                </template>
              </el-table-column>

              <!-- 自动退款了的 显示已退款
              其他显示退款按钮
              退款操作中显示退款中 -->
              <el-table-column label="Operate" align="center" width="100">
                <template slot-scope="{ row }">
                  <el-button
                    v-if="!refundObj.loading && row.paymentStatus !== 'Refund Successfully'"
                    type="danger"
                    size="small"
                    @click="toRefund(row)"
                  >
                    退款
                  </el-button>
                  <el-tag
                    v-if="!refundObj.loading && row.paymentStatus == 'Refund Successfully'"
                    type="info"
                  >已退款</el-tag
                  >
                  <el-tag
                    v-if="refundObj.id == row.id && refundObj.loading"
                  >退款中</el-tag
                  >
                </template>
              </el-table-column>
            </el-table>

            <div v-if="total[0] > 0" class="fr-pagination">
              <el-pagination
                :current-page="listQuery[0].pageNum"
                :page-sizes="[15, 20, 30]"
                :page-size="listQuery[0].pageSize"
                :total="total[0]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="(val) => handlePageChange(val, 0, 'pageSize')"
                @current-change="(val) => handlePageChange(val, 0, 'pageNum')"
              />
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>

      <el-tab-pane label="后台手动充值" name="1">
        <div class="top-search">
          <el-date-picker
            v-model="datePicker[1]"
            class="w-240"
            type="daterange"
            align="right"
            value-format="yyyy-MM-dd"
          />
          <el-select v-model="listQuery[1].operatorType" class="w-240">
            <el-option
              v-for="item in operatorsOption"
              :label="item.label"
              :value="item.value"
              :key="item.label"
            />
          </el-select>
          <el-input
            :value="listQuery[1].mobile"
            class="w-240"
            placeholder="充值号码"
            clearable
            @input="
              (value) => (listQuery[1].mobile = value.replace(/[^\d]/g, ''))
            "
          />
          <el-input
            :value="listQuery[1].id"
            class="w-240"
            placeholder="ID"
            clearable
            @input="
              (value) => (listQuery[1].id = value.replace(/[^\d]/g, ''))
            "
          />
          <el-button type="primary" @click="search(1)">搜索</el-button>
          <el-button
            :disabled="total[1] == 0"
            class="fr"
            type="primary"
            @click="toExport(1)"
            >导出</el-button
          >
          <span class="summary_total fr"> {{ $t('total_amount') }}: {{ billTotal[activeName] }} </span>
        </div>

        <el-row>
          <el-col class="p-t-20">
            <el-table
              v-loading="listLoading[1]"
              :data="listData[1]"
              border
              fit
              highlight-current-row
            >
              <el-table-column label="Serial number" width="80" align="center">
                <template slot-scope="scope">
                  <span>{{
                    (listQuery[1].pageNum - 1) * listQuery[1].pageSize +
                      scope.$index +
                      1
                  }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="Mobile/Account"
                prop="mobile"
                align="center"
              />

              <el-table-column
                label="Telecom Operator"
                prop="rechargeOperator"
                align="center"
              />

              <el-table-column label="Amount（$）" prop="amount" align="center"/>

              <el-table-column label="ID" prop="id" align="center"/>

              <el-table-column
                label="Transaction_id"
                prop="transactionId"
                align="center"
              />

              <el-table-column label="Complete Time" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.createTime | fmtdate }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="Order Status"
                prop="status"
                align="center"
              />

              <el-table-column label="Operate" align="center" width="120">
                <template slot-scope="{ row }">
                  <el-button type="primary" @click="edit(row, 1)">
                    修改状态
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div v-if="total[1] > 0" class="fr-pagination">
              <el-pagination
                :current-page="listQuery[1].pageNum"
                :page-sizes="[15, 20, 30]"
                :page-size="listQuery[1].pageSize"
                :total="total[1]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="(val) => handlePageChange(val, 1, 'pageSize')"
                @current-change="(val) => handlePageChange(val, 1, 'pageNum')"
              />
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <!-- 修改状态 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      title="修改状态"
      width="600px"
    >
      <p class="title">请选择充值订单状态:</p>
      <el-radio-group v-model="form.status">
        <el-radio :label="1">充值成功</el-radio>
        <el-radio :label="0">充值失败</el-radio>
      </el-radio-group>

      <div slot="footer" class="dialog-footer">
        <el-button
          :disabled="btnLoading"
          :loading="btnLoading"
          @click="dialogVisible = false"
        >取 消</el-button
        >
        <el-button
          :disabled="btnLoading"
          :loading="btnLoading"
          type="primary"
          @click="sureReject"
        >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBillListApi,
  getManualListApi,
  getBillTotal,
  getManualBillTotal,
  refundApi,
  updateStatusApi,
  updateRechargeStatusApi
} from '@/api/recharge-reconciliation.js'
import { getToken } from '@/utils/auth'
import timeUtils from '@/utils/timeHandle.js'
import { dateShortcutKeyJS } from '@/mixins/index.js'

export default {
  data() {
    return {
      datePicker: [
        [
          timeUtils.timeHandle(
            new Date().getTime() - 3600 * 1000 * 24 * 29,
            'date'
          ),
          timeUtils.timeHandle(new Date().getTime(), 'date')
        ],
        [
          timeUtils.timeHandle(
            new Date().getTime() - 3600 * 1000 * 24 * 29,
            'date'
          ),
          timeUtils.timeHandle(new Date().getTime(), 'date')
        ]
      ],
      activeName: '0',
      listQuery: [
        {
          memberId: null,
          paymentType: null, // 支付方式  1:支付宝 2:微信 3:mpay 4:汇旺 5:pipay 6:wing 10:零钱
          releaseTimeStart: null,
          releaseTimeEnd: null,
          operatorType: null, // 2：smart 3:cellcard 4:metfone 111:seatel
          mobile: null,
          orderSn: '', // 订单号
          pageNum: 1,
          pageSize: 15
        },
        {
          releaseTimeStart: null,
          releaseTimeEnd: null,
          operatorType: null, // 2：smart 3:cellcard 4:metfone 111:seatel
          mobile: null,
          pageNum: 1,
          pageSize: 15,
          id: '' // 订单号
        }
      ],
      exportQuery: [
        {
          memberId: null,
          paymentType: null, // 支付方式  1:支付宝 2:微信 3:mpay 4:汇旺 5:pipay 6:wing 10:零钱
          releaseTimeStart: null,
          releaseTimeEnd: null,
          operatorType: null, // 2：smart 3:cellcard 4:metfone 111:seatel
          mobile: null,
          pageNum: 1,
          pageSize: 15
        },
        {
          releaseTimeStart: null,
          releaseTimeEnd: null,
          operatorType: null, // 2：smart 3:cellcard 4:metfone 111:seatel
          mobile: null,
          pageNum: 1,
          pageSize: 15
        }
      ],
      listData: [[], []],
      billTotal: [],
      total: [0, 0],
      listLoading: [false, false],
      refundObj: {
        loading: false,
        id: null
      },
      btnLoading: false,
      dialogVisible: false,
      operatorsOption: [
        {
          label: '请选择电讯运营商',
          value: null
        },
        {
          label: 'Smart',
          value: '2'
        },
        {
          label: 'Cellcard',
          value: '3'
        },
        {
          label: 'Metfone',
          value: '4'
        },
        {
          label: 'Seatel',
          value: '111'
        }
      ],
      payMethodOption: [
        {
          label: '请选择支付方式',
          value: null
        },
        {
          label: 'Alipay',
          value: '1'
        },
        {
          label: 'Wechat',
          value: '2'
        },
        {
          label: 'Mpay',
          value: '3'
        },
        {
          label: 'Huione',
          value: '4'
        },
        {
          label: 'Pipay',
          value: '5'
        },
        {
          label: 'Wing',
          value: '6'
        },
        {
          label: 'Balance',
          value: '10'
        }
      ],
      form: {
        id: null,
        status: null
      },
      paymentTypeMap: {
        Alipay: 1,
        Wechat: 2,
        Mpay: 3,
        Huione: 4,
        Pipay: 5,
        Wing: 6,
        'Wechat Official Accounts': 7,
        Balance: 10
      }
    };
  },

  computed: {
    serializedQuery() {
      const removeEmpty = obj =>
        Object.keys(obj)
          .filter(k => obj[k] != null && obj[k] !== '')
          .reduce((r, k) => ({ ...r, [k]: obj[k] }), {});
      const { mobile, ...rest } = this.listQuery[this.activeName];
      return removeEmpty({
        ...rest,
        mobile: mobile ? `${mobile}`.replace(/^0/, '') : ''
      });
    }
  },

  created() {
    this.search(0);
    this.search(1);
  },

  methods: {
    async getListAndTotal(index) {
      this.$set(this.listLoading, index, true);
      try {
        await Promise.all([this.getList(index), this.getTotal(index)]);
      } catch (e) {
        this.$message.error(e.message);
      } finally {
        this.$set(this.listLoading, index, false);
      }
    },

    async getTotal(index) {
      const api = index == 0 ? getBillTotal : getManualBillTotal;
      const res = await api(this.serializedQuery);
      const { state, result, error_msg: errMsg } = res;
      this.$set(this.listLoading, index, false);
      if (state == 1) {
        this.billTotal[index] = result;
      } else {
        throw new Error(errMsg);
      }
    },

    async getList(index) {
      const api = index == 0 ? getBillListApi : getManualListApi;
      const query = this.serializedQuery;
      this.exportQuery[index] = query;

      const { state, result, error_msg } = await api(query);
      if (state == 1) {
        this.listData[index] = result.list || [];
        this.total[index] = Number(result.total) || 0;
      } else {
        throw new Error(error_msg);
      }
    },

    search(index) {
      if (!this.datePicker[index] || this.datePicker[index].length == 0) {
        this.$message.warning('筛选时间不能为空');
        return;
      }

      this.listQuery[index].pageNum = 1;
      this.listQuery[index].releaseTimeStart =
        this.datePicker[index][0] || null;
      this.listQuery[index].releaseTimeEnd = this.datePicker[index][1] || null;
      this.getListAndTotal(index);
    },

    toExport(index) {
      // eslint-disable-next-line
      let {
        memberId,
        releaseTimeStart,
        releaseTimeEnd,
        mobile,
        operatorType,
        paymentType
      } = this.exportQuery[index];

      if (
        !releaseTimeStart ||
        !releaseTimeEnd ||
        new Date(releaseTimeEnd) - new Date(releaseTimeStart) > 7776000000
      ) {
        this.$message.warning('最多可导出三个月内的数据，请先调整筛选时间范围');
        return;
      }

      mobile = mobile && mobile[0] == 0 ? mobile.slice(1) : mobile;

      const typeQuery = `?type=${index + 1}`;
      const startQuery = releaseTimeStart
        ? '&releaseTimeStart=' + releaseTimeStart
        : '';
      const endQuery = releaseTimeEnd
        ? '&releaseTimeEnd=' + releaseTimeEnd
        : '';
      const memberIdQuery = memberId ? '&memberId=' + memberId : '';
      const mobileQuery = mobile ? '&mobile=' + mobile : '';
      const paymentTypeQuery = paymentType ? '&paymentType=' + paymentType : '';
      const operatorTypeQuery = operatorType
        ? '&operatorType=' + operatorType
        : '';

      var xhh = new XMLHttpRequest();
      xhh.open(
        'get',
        process.env.LIFE_ADMIN_API +
          '/shop/bill/export' +
          typeQuery +
          startQuery +
          endQuery +
          memberIdQuery +
          mobileQuery +
          paymentTypeQuery +
          operatorTypeQuery
      );
      xhh.setRequestHeader('x-auth-token', getToken());
      xhh.responseType = 'blob';
      xhh.onreadystatechange = function() {
        if (xhh.readyState === 4 && xhh.status === 200) {
          var blob = new Blob([xhh.response]);
          var csvUrl = URL.createObjectURL(blob);
          var link = document.createElement('a');
          var fileName = xhh
            .getResponseHeader('Content-Disposition')
            .split(';')[1]
            .split('filename=')[1];
          var fileNameUnicode = xhh
            .getResponseHeader('Content-Disposition')
            .split('filename*=')[1];
          if (fileNameUnicode) {
            fileName = decodeURIComponent(fileNameUnicode.split("''")[1]);
          }

          document.body.appendChild(link);
          link.href = csvUrl;
          link.target = '_blank';
          link.id = 'linkId';
          link.className = 'linkId';
          link.download = decodeURI(fileName);
          document.getElementById('linkId').click();
          link.remove();
        }
      };
      xhh.send();
    },

    handlePageChange(val, index, name) {
      this.listQuery[index][name] = val;
      this.getListAndTotal(index);
    },

    // 修改用户充值  手动充值状态 调用不同的接口
    async sureReject() {
      this.btnLoading = true
      const index = this.activeName;
      const api = index == 1 ? updateStatusApi: updateRechargeStatusApi
      try {
        const { state, error_msg } = await api(this.form)
        this.btnLoading = false
        if (state == 1) {
          this.dialogVisible = false
          this.$message.success('操作成功')
          this.getList(index)
          this.getListAndTotal(index);
        } else {
          this.$message.warning(error_msg);
        }
      } catch (e) {
        this.btnLoading = false;
      }
    },

    async toRefund(row) {
      const { id, paymentType, orderSn } = row;

      try {
        const action = await this.$confirm('确定要执行退款操作吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        });

        if (action === 'confirm') {
          this.refundObj.id = id;
          const query = {
            paymentType: this.paymentTypeMap[paymentType],
            orderSn
          };
          this.sureRefund(query);
        }
      // eslint-disable-next-line no-empty
      } catch (e) {}
    },

    async sureRefund(query) {
      this.refundObj.loading = true;
      try {
        const { state, error_msg } = await refundApi(query);
        this.refundObj.id = null;
        this.refundObj.loading = false;
        if (state == 1) {
          this.$message.success('操作成功');
          this.getListAndTotal(0);
        } else {
          this.$message.warning(error_msg);
        }
      } catch (e) {
        this.refundObj.id = null;
        this.refundObj.loading = false;
      }
    },

    edit(row, type) {
      const { id, status, topUpStatus } = row
      const currentStatus = type == 1 ? status : topUpStatus
      this.form = {
        id,
        status: currentStatus == 'Completed' ? 1 : 0
      }
      this.dialogVisible = true
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 15px;
  .top-search {
    margin: 10px 0;
  }
  .title {
    font-size: 16px;
    line-height: 36px;
  }
}

.container /deep/ th {
  div {
    word-break: break-word;
  }
}

.summary_total {
  color: #303133;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
}
</style>
